<template>
  <div>
    <el-button @click="handleClick" :size="size" :loading="btnLoading">{{ title }}</el-button>
    <input class="inputClass" ref="fileInput" type="file"  accept=".xls,.xlsx" @change="readExcel">
  </div>
</template>

<script setup>
import * as XLSX from 'xlsx'
import {ref} from 'vue'
const fileName = ref('')
const fileInput = ref()
const props = defineProps({
  onSuccess: Function,
  title:{
    type: String,
    default: '导入'
  },
  size:{
    type: String,
    default: 'small'
  }
})
const btnLoading = ref(false)
const handleClick = () => {
  fileInput.value.click()
}
const readExcel = (event) => {
  console.log(123)
  const { files } = event.target
  if(files.length <= 0){
    return
  } else if(!/.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
    return this.$message.warning('上传格式不正确，请上传xls或xlsx格式')
  }else {
    fileName.value = files[0].name // 拿到excel文件名
  }
  // 读取文件
  const fileReader = new FileReader()
  fileReader.onload = ev => {
    try {
      const data = ev.target.result
      const workbook = XLSX.read(data,{type: 'binary'})
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const result = XLSX.utils.sheet_to_json(worksheet)
      const header =  getHeaderRow(worksheet)
      props.onSuccess({result, header, fileName: fileName.value})

    } catch (error) {}
  }
  fileReader.readAsBinaryString(files[0])
}

// 获取头部
const getHeaderRow = (sheet) => {
  const headers = []
  const range = XLSX.utils.decode_range(sheet['!ref'])
  let C
  const R = range.s.r
  /* start in the first row */
  for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
    const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
    /* find the cell in the first row */
    let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
    if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
    headers.push(hdr)
  }
  return headers
}
</script>

<style scoped lang='scss'>
.inputClass{
  opacity: 0;
  position: fixed;
  top: 99999px;
}
</style>
